package netty.chat.utils;

import com.sun.xml.internal.bind.v2.util.ByteArrayOutputStreamEx;

import java.io.*;

/**
 * Created by Administrator on 2015/10/12.
 */
public class ObjectUtils {

    public static byte[] toBytes(Object obj){
        byte[] bytes = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStreamEx();
        ObjectOutputStream oo = null;
        try {
            oo = new ObjectOutputStream(outputStream);
            oo.writeObject(obj);
            bytes = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                oo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    public static Object toObject(byte[] bytes) {
        Object obj = null;
        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
        ObjectInputStream oi = null;
        try {
            oi = new ObjectInputStream(bi);
            obj = oi.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bi.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                oi.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }

}
